<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <el-button type="primary" icon="el-icon-plus" @click="add" v-auth="'directpurchase.add'" ></el-button>
                <el-button type="danger" plain icon="el-icon-delete" :disabled="selection.length == 0" @click="batch_del" v-auth="'directpurchase.delete'" ></el-button>
            </div>
            <div class="right-panel">
                <div class="right-panel-search">
                    <el-input v-model="search.purchase_code" placeholder="采购编号" clearable @keyup.enter="upsearch"></el-input>
                    <el-select v-model="search.apply_id" placeholder="供应商" filterable clearable>
                        <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                    </el-select>
                    <el-date-picker v-model="search.purchase_date" :value-format="'YYYY-MM-DD'" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                    <el-select v-model="search.is_complate" placeholder="请选择状态" filterable clearable>
                        <el-option label="未完" :value="0"></el-option>
                        <el-option label="已完成" :value="1"></el-option>
                        <el-option label="全部" :value="10"></el-option>
                    </el-select>
                    <el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
                    <el-button type="primary" icon="el-icon-refresh" @click="refresh"></el-button>
                </div>
            </div>
        </el-header>
        <el-main class="nopadding">
            <scTable ref="table" :apiObj="apiObj" row-key="id" @selection-change="selectionChange" :params="{no_plan: 1}" tableName="purchaseTable" :column="purchaseColumn">
                <el-table-column type="selection" width="50" align="center"></el-table-column>
                <template #purchase_code="{row}">
                    <div class="flex" style="flex-direction: column;align-items: flex-start">
                        <div class="flex">
                            <el-link :underline="false" type="primary" @click="table_show(row)">{{ row.purchase_code }}</el-link>
                            <el-icon class="icon" :size="20" @click="common.copy(row.purchase_code)"><el-icon-Edit /></el-icon>
                            <el-icon class="icon" :size="20" color="#29f" @click="table_bell(row)" v-auth="'directpurchase.message'"><el-icon-BellFilled /></el-icon>
                        </div>
                        <div class="margin">{{row.purchase_date}}</div><!-- ({{row.area_name}}) -->
                    </div>
                </template>
                <template #total_num="{row}">
                    <div>交货： <span style="color: #29f">-{{row.total_num}} </span></div>
                    <div class="margin">备注：<el-icon v-auth="'directpurchase.remark'" class="icon" color="#1e9fff" :size="18" @click="table_remark(row)"><el-icon-EditPen /></el-icon> <span>{{row.remark}}</span></div>
                </template>
                <template #progress="{row}">
                    <div class="progress" @click="table_show(row)">
                        <div style="margin-bottom: 5px">{{row.deliver_num}}/{{row.total_num}}</div>
                        <el-progress style="width: 100%" :percentage="((row.deliver_num / row.total_num) * 100)" :show-text="false"></el-progress>
                    </div>
                </template>
                <template #status="{row}">
                    <el-button :type="row.status == 0 ? 'warning' : row.status == 1 ? 'primary' : 'danger'" size="small" @click="table_check(row)" v-auth="'directpurchase.check'">{{row.status == 0 ? '待审' : row.status == 1 ? '通过' : '退回'}}</el-button>
                </template>
                <template #upload="{row}">
                    <el-button type="primary" size="small" @click="table_upload(row)" v-if="row.status == 1" v-auth="'purchase.upload'">查看</el-button>
                </template>
                <template #purchasestaff="{row}">
                    <div class="flex">
                        <div>{{row.purchasestaff && row.purchasestaff.name}}</div>
                        <el-icon class="icon" :size="16" @click="table_staff(row)"><el-icon-UserFilled /></el-icon>
                    </div>
                </template>
                <template #operation="scope">
                    <div class="buttonFlex">
                        <el-popconfirm :title="`确定${scope.row.is_complate == 1 ? '未完' : '完成'}吗？`" @confirm="purchase_complate(scope.row)">
                            <template #reference>
                                <el-button type="default" size="small" v-auth="'purchase.complate'">{{scope.row.is_complate == 1 ? '完成' : '未完'}}</el-button>
                            </template>
                        </el-popconfirm>
                        <el-popconfirm :title="scope.row.freeze == 0 ? '确定冻结吗？' : '确定撤销冻结吗？'" @confirm="table_freeze(scope.row, scope.$index)">
                            <template #reference>
                                <el-button size="small" v-auth="'directpurchase.freeze'">{{scope.row.freeze == 0 ? '冻结' : '撤销冻结'}}</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button size="small" @click="table_print(scope.row)" v-auth="'directpurchase.print'">打印</el-button>
                        <el-button type="primary" size="small" @click="table_edit(scope.row)" v-auth="'directpurchase.edit'" v-if="scope.row.status != 1">编辑</el-button>
                        <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                            <template #reference>
                                <el-button type="danger" size="small" v-auth="'directpurchase.delete'" v-if="scope.row.status != 1">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                    <div class="buttonFlex">
                        <el-button size="small" @click="table_settle(scope.row)" v-auth="'directpurchase.settle'">结账单</el-button>
                        <el-button size="small" @click="table_copy(scope.row)" v-auth="'directpurchase.copy'">复制</el-button>
                        <el-button size="small" @click="table_inhouse(scope.row)" v-auth="'directpurchasehouse.add'" v-if="scope.row.status == 1">入库</el-button>
                        <el-button size="small" @click="table_inrecord(scope.row)" v-auth="'directpurchasehouse.inrecord'">入库记录</el-button>
                    </div>
                </template>


                <!-- <el-table-column label="采购编号" prop="purchase_code" width="250">
                    <template #default="{row}">
                        <div class="flex" style="flex-direction: column;align-items: flex-start">
                            <div class="flex">
                                <el-link type="primary" @click="table_show(row)">{{ row.purchase_code }}</el-link>
                                <el-icon class="icon" :size="20" @click="common.copy(row.purchase_code)"><el-icon-Edit /></el-icon>
                                <el-icon class="icon" :size="20" color="#29f" @click="table_bell(row)" v-auth="'purchase.message'"><el-icon-BellFilled /></el-icon>
                            </div>
                            <div class="margin">{{row.purchase_date}}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column>
                    <template #default="{row}">
                        <div>交货： <span style="color: #29f">-{{row.total_num}} </span></div>
                        <div class="margin">备注：<el-icon v-auth="'purchase.remark'" class="icon" color="#1e9fff" :size="18" @click="table_remark(row)"><el-icon-EditPen /></el-icon> <span>{{row.remark}}</span></div>
                    </template>
                </el-table-column>
                <el-table-column label="入库进度" prop="state" width="130" align="center">
                    <template #default="{row}">
                        <div class="progress" @click="table_show(row)">
                            <div style="margin-bottom: 5px">{{row.deliver_num}}/{{row.total_num}}</div>
                            <el-progress style="width: 100%" :percentage="((row.deliver_num / row.total_num) * 100)" :show-text="false"></el-progress>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="审核" prop="status" width="130" align="center">
                    <template #default="{row}">
                        <el-button :type="row.status == 0 ? 'warning' : row.status == 1 ? 'primary' : 'danger'" size="small" @click="table_check(row)" v-auth="'purchase.check'">{{row.status == 0 ? '待审' : row.status == 1 ? '通过' : '退回'}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="签名" prop="upload" width="130" align="center">
                    <template #default="{row}">
                        <el-button type="primary" size="small" @click="table_upload(row)" v-if="row.status == 1" v-auth="'purchase.upload'">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="业务员" prop="purchasestaff" width="130" align="center">
                    <template #default="{row}">
                        <div class="flex">
                            <div>{{row.purchasestaff && row.purchasestaff.name}}</div>
                            <el-icon class="icon" :size="16" @click="table_staff(row)"><el-icon-UserFilled /></el-icon>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="300">
                    <template #default="scope">
                        <div class="buttonFlex">
                            <el-popconfirm :title="scope.row.freeze == 0 ? '确定冻结吗？' : '确定撤销冻结吗？'" @confirm="table_freeze(scope.row, scope.$index)">
                                <template #reference>
                                    <el-button size="small" v-auth="'purchase.freeze'">{{scope.row.freeze == 0 ? '冻结' : '撤销冻结'}}</el-button>
                                </template>
                            </el-popconfirm>
                            <el-button size="small" @click="table_print(scope.row)" v-auth="'purchase.print'">打印</el-button>
                            <el-button type="primary" size="small" @click="table_edit(scope.row)" v-auth="'purchase.edit'" v-if="scope.row.status != 1">编辑</el-button>
                            <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                                <template #reference>
                                    <el-button type="danger" size="small" v-auth="'purchase.delete'" v-if="scope.row.status != 1">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                        <div class="buttonFlex">
                            <el-button size="small" @click="table_settle(scope.row)" v-auth="'purchase.copy'">结账单</el-button>
                            <el-button size="small" @click="table_copy(scope.row)" v-auth="'purchase.copy'">复制</el-button>
                            <el-button size="small" @click="table_inhouse(scope.row)" v-auth="'purchasehouse.add'" v-if="scope.row.status == 1">入库</el-button>
                            <el-button size="small" @click="table_inrecord(scope.row)" v-auth="'purchasehouse.inrecord'">入库记录</el-button>
                        </div>
                    </template>
                </el-table-column> -->
            </scTable>
        </el-main>
    </el-container>
    <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>
    <check-status v-if="dialog.check" ref="checkDialog" @success="handleSuccess" @closed="dialog.check = false" draggable></check-status>
    <upload-dialog v-if="dialog.upload" ref="uploadDialog" @success="handleSuccess" @closed="dialog.upload = false"></upload-dialog>
    <look-list v-if="dialog.look" ref="lookDialog" @success="handleSuccess" @closed="dialog.look = false" :query="{purchase_id: purchase_id}"></look-list>
    <arrival-dialog v-if="dialog.arrival" ref="arrivalDialog" @success="handleSuccess" @closed="dialog.arrival = false"></arrival-dialog><!-- 入库 -->
    <select-house v-if="dialog.house" ref="houseDialog" @success="houseBack" @closed="dialog.house = false" :query="{purchase_id: purchase_id}"></select-house><!-- 入库记录 -->
    <notice-save v-if="dialog.notice" ref="noticeDialog" @success="handleSuccess" @closed="dialog.notice = false"></notice-save>
    <settle-save v-if="dialog.settle" ref="settleDialog" @success="handleSuccess" @closed="dialog.settle = false"></settle-save>
    <remark-save v-if="dialog.remark" ref="remarkDialog" @success="handleSuccess" @closed="dialog.remark = false"></remark-save>

    <el-dialog title="打印" width="500" v-model="dialog.print_select" align-center>
        <el-form label-position="top">
            <el-form-item label="打印关联单">
                <el-select v-model="is_correlation">
                    <el-option label="是" :value="1"></el-option>
                    <el-option label="否" :value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="打印价格"> 
                <el-select v-model="is_price">
                    <el-option label="是" :value="1"></el-option>
                    <el-option label="否" :value="0"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="open_print">打 印</el-button>
        </template>
    </el-dialog>
    <pruchase-print v-if="dialog.print" ref="printDialog" @success="handleSuccess" @closed="dialog.print = false"></pruchase-print>
    
</template>

<script>
import saveDialog from './save'
import CheckStatus from '../../checkStatus.vue'
import uploadDialog from '../../upload.vue'
import LookList from '../purchase/lookList.vue'
import SelectHouse from '../../selectHouse.vue';
import RemarkSave from '../../remarkSave.vue'
import arrivalDialog from '../arrival/save'
import pruchasePrint from '../purchase/pruchasePrint.vue'
import SettleSave from '../purchase/settleSave.vue'
import NoticeSave from '../../noticeSave.vue'

export default {
    name: '采购计划管理',
    components: {
        saveDialog,
        CheckStatus,
        uploadDialog,
        LookList,
        SelectHouse,
        RemarkSave,
        pruchasePrint,
        SettleSave,
        NoticeSave,
        arrivalDialog,
    },
    data() {
        return {
            dialog: {
                save: false,
                check: false,
                upload: false,
                look: false,
                arrival: false,
                house: false,
                settle: false,
                remark: false,
            },
            apiObj: this.$API.business.purchase.order.list,
            selection: [],
            search: {
                keyword: null,
                field: null,
                purchase_date: [this.moment().subtract(30, 'days').format('YYYY-MM-DD'), this.moment().format('YYYY-MM-DD')],
                status: null,
                is_complate: 0,
            },
            applyList: [],
            purchase_id: "",
            print_id: "",
            is_correlation: 1,
            is_price: 1,
            purchaseColumn: [
                { label: "采购编号", prop: "purchase_code", width: "250",align: "left" },
                { label: "", prop: "total_num", align: "left" },
                { label: "品名", prop: "goods_name",width: "130", },
                { label: "供应商", prop: "apply.apply_name",width: "130", },
                { label: "入库进度", prop: "progress",width: "130", },
                { label: "审核", prop: "status",width: "130", },
                { label: "签名", prop: "upload",width: "130", },
                { label: "业务员", prop: "purchasestaff",width: "130", },
                { label: "操作", prop: "operation", width: "300",},
            ],
        }
    },
    mounted() {
		this.getApply();
        if(this.$route.query.code) {
            this.search.purchase_code = this.$route.query.code
            this.upsearch()
        }
    },
    methods: {
        //添加
        add() {
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open()
            })
        },
        //编辑
        table_edit(row) {
            if(row.freeze == 1){
                this.$message.error("该采购单已冻结，请解冻后再进行编辑！")
                return
            }
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('edit').setData(row)
            })
        },
        //查看
        table_show(row) {
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('show').setData(row)
            })
        },
        //删除
        async table_del(row) {
            var reqData = { id: row.id }
            var res = await this.$API.business.purchase.order.delete.post(reqData);
            if (res.code == 1) {
                this.$refs.table.refresh()
                this.$message.success("删除成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        async table_del_all(delete_ids) {
            var reqData = { id: delete_ids }
            var res = await this.$API.business.purchase.order.delete.post(reqData);
            if (res.code == 1) {
                this.$refs.table.refresh()
                this.$message.success("删除成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        //批量删除
        async batch_del() {
            var delete_ids = [];
            this.selection.forEach((item) => {
                delete_ids.push(item.id)
            })

            this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
                type: 'warning'
            }).then(() => {
                this.table_del_all(delete_ids)
            }).catch(() => {

            })
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selection = selection;
        },
        //搜索
        upsearch() {
            this.$refs.table.upData(this.search)
        },
        //本地更新数据
        handleSuccess(data, mode) {
            if (mode == 'add') {
                this.$refs.table.refresh()
            } else if (mode == 'edit') {
                this.$refs.table.refresh()
            } else if (mode == 'purchase') {
                this.$refs.table.refresh()
            }
        },
        refresh() {
            for (const key in this.search) {
                this.search[key] = null;
            }
            this.search.is_complate = 0
            this.search.purchase_date = [this.moment().subtract(30, 'days').format('YYYY-MM-DD'), this.moment().format('YYYY-MM-DD')],
            this.$refs.table.upData(this.search)
        },
        // 供应商列表
		async getApply() {
			var res = await this.$API.basic.apply.all.get({type: 1});
			this.applyList = res.data
		},
        // 采购复制
        table_copy(row){
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('copy').setData(row,1)
            })
        },
        // 采购审核
        table_check(row){
            if(row.freeze == 1){
                this.$message.error("该采购单已冻结，请解冻后再进行审核！")
                return
            }
            this.dialog.check = true
            this.$nextTick(() => {
                this.$refs.checkDialog.open('purchase').setData(row,row.checkstaff?.name)
            })
        },
        // 查看签名
        table_upload(row){
            this.dialog.upload = true
            this.$nextTick(() => {
                this.$refs.uploadDialog.open('show').setData(row)
            })
        },
        // 采购完成
        async purchase_complate(row){
            var reqData = { id: row.id }
            var res = await this.$API.business.purchase.order.complate.post(reqData);
            if (res.code == 1) {
                this.$refs.table.refresh()
                this.$message.success("操作成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        //  采购冻结/反冻结
        async table_freeze(row) {
            var reqData = {
                id: row.id,
                freeze: row.freeze == 1 ? 0 : 1
            }
            var res = await this.$API.business.purchase.order.freeze.post(reqData);
            if (res.code == 1) {
                this.$refs.table.refresh()
                this.$message.success("操作成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        // 查看采购员
        table_staff(row){
            this.purchase_id = row.id
            this.dialog.look = true
            this.$nextTick(() => {
                this.$refs.lookDialog.open('edit')
            })
        },
        // 采购入库
        table_inhouse(row){
            this.dialog.arrival = true
            this.$nextTick(() => {
                this.$refs.arrivalDialog.open('add').getData(row)
            })
        },
        // 入库记录
        table_inrecord(row){
            this.purchase_id = row.id
            this.dialog.house = true
            this.$nextTick(() => {
                this.$refs.houseDialog.open('add')
            })
        },
        // 采购提醒
        table_bell(row){
            let data = {
                id: row.id,
                code: row.purchase_code,
                apply_id: row.apply_id
            }
            this.dialog.notice = true
            this.$nextTick(() => {
                this.$refs.noticeDialog.open('edit').setData(data,'采购单',1)
            })
        },
        
        // 采购单备注
        table_remark(row){
            this.dialog.remark = true
            this.$nextTick(() => {
                this.$refs.remarkDialog.open('purchase').setData(row)
            })
        },

        // 打印选择弹窗
        table_print(row){
            this.print_id = row.id;
            this.dialog.print_select = true;
        },
        // 确定打印
        open_print(){
            let query = {
                id: this.print_id,
                is_correlation: this.is_correlation,
                is_price: this.is_price,
            }
            this.dialog.print_select = false;
            this.dialog.print = true;
            this.$nextTick(() => { 
                this.$refs.printDialog.open('print').setData(query)
            })
            this.is_correlation = 1
            this.is_price = 1
        },

        // 结算
        table_settle(row){
            this.purchase_id = row.id
            this.dialog.house = true
            this.$nextTick(() => {
                this.$refs.houseDialog.open('add').setData(1)
            })
            // this.dialog.settle = true;
            // this.$nextTick(() => { 
            //     this.$refs.settleDialog.open('edit').setData(row)
            // })
        },
        houseBack(data){
            let array = []
            data.map(item=>{
                array.push(item.id)
            })
            let row = {
                id: this.purchase_id,
                purchase_ware_ids: array
            }
            this.dialog.settle = true;
            this.$nextTick(() => { 
                this.$refs.settleDialog.open('edit').setData(row)
            })
        },
    }
}
</script>

<style></style>
